<template>
  <div>
    <!-- 视频显示区域 -->
    <video id="video" width="400" height="300" autoplay></video>
    <!-- 人脸识别按钮 -->
    <el-button @click="captureImage">拍照</el-button>
    <!-- 捕获的图像显示区域 -->
    <canvas id="canvas" width="400" height="300" style="display:none;"></canvas>
  </div>
</template>

<script>
export default {
  data() {
    return {
      stream: null, // 媒体流对象
    };
  },
  mounted() {
    this.startVideo();
  },
  methods: {
    async startVideo() {
      try {
        this.stream = await navigator.mediaDevices.getUserMedia({ video: true });
        const video = this.$el.querySelector('video');
        video.srcObject = this.stream;
      } catch (error) {
        console.error('Error accessing media devices.', error);
      }
    },
    captureImage() {
      const video = this.$el.querySelector('video');
      const canvas = this.$el.querySelector('canvas');
      const ctx = canvas.getContext('2d');

      // 将视频帧绘制到canvas上
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

      // 这里你可以将canvas转换为图像数据
      const imageData = canvas.toDataURL('image/png');

      // 调用人脸识别API，将图像数据发送到后端
      this.faceRecognition(imageData);
    },
    faceRecognition(imageData) {
      // 这里应该是调用后端人脸识别API的代码
      // 你可以将imageData发送到后端进行人脸识别
      console.log('Image data for face recognition:', imageData);
    },
    stopVideo() {
      if (this.stream) {
        this.stream.getTracks().forEach(track => track.stop());
        this.stream = null;
      }
    }
  },
  beforeDestroy() {
    this.stopVideo();
  }
};
</script>
